package tq.com.tqteacher.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.browser.DetailPicsActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import tq.com.systools.system.AlertDialogHelper;
import tq.com.tqcom.base.BaseFragment;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.net.TQPictureUpload;
import tq.com.tqcom.util.TQSystemDefine;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.activity.TQDirectoryActivity;
import tq.com.tqteacher.activity.TQPdfReaderActivity;
import tq.com.tqteacher.activity.playerView.TQPlayerActivity;
import tq.com.tqteacher.adapt.TQDirectoryAdapter;
import tq.com.tqteacher.adapt.TQDirectoryDetailAdapter;
import tq.com.tqteacher.model.TQDirectoryModel;
import tq.com.tqteacher.model.TQFileInfo;
import tq.com.tqteacher.model.TQNewPublish;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.net.TQNetInterface;

public class TQDirectoryFragment extends BaseFragment {
    private RecyclerView mRecyclerView;
    private TQDirectoryAdapter mTQDirectoryAdapter;
    private TQHeader5View mHeader5View;
    private SmartRefreshLayout mRefreshLayout;

    private int requestType = 0x00;
    private int loadFileType = TQSystemDefine.FILE_TYPE_ALL;

    private int type = 0; //0 for home page . 1 for others
    private int page = 1;

    static public TQDirectoryFragment showWithType(int t, int pLoadFileType){
        TQDirectoryFragment lFragment = new TQDirectoryFragment();
        lFragment.type = t;
        lFragment.loadFileType = pLoadFileType;
        return lFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View lView = inflater.inflate(R.layout.fragment_recyclerview_layout, container, false);
        mRecyclerView = lView.findViewById(R.id.recyclerView);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        if(mTQDirectoryAdapter == null){
            mTQDirectoryAdapter =  new TQDirectoryAdapter(getContext());
            mTQDirectoryAdapter.setFileClickListener(mFileClickListener);
        }
        mHeader5View = lView.findViewById(R.id.title);
        mHeader5View.getBackIcon().setVisibility(type == 1 ? View.VISIBLE : View.INVISIBLE);
        mHeader5View.getTitleView().setText("文件夹");
        mHeader5View.getBackIcon().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });


        requestType = getActivity().getIntent().getIntExtra(TQDirectoryActivity.REQUEST_SELECT_KEY, 0x00);

        mRecyclerView.setAdapter(mTQDirectoryAdapter);
        mRefreshLayout = lView.findViewById(R.id.refresh);
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                Log.d(TAG, "onLoadMore: ");
                page++;
                loadFile();
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                Log.d(TAG, "onRefresh: ");
                page = 1;
                loadFile();
            }
        });
        mRefreshLayout.autoRefresh();
        return lView;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    private TQDirectoryDetailAdapter.IFileClickListener mFileClickListener = new TQDirectoryDetailAdapter.IFileClickListener() {
        @Override
        public void itemClick(TQFileInfo file) {
            if(type == 1){
                if(requestType == 0x01) {
                    if(loadFileType == TQSystemDefine.FILE_TYPE_PDF){
                        startPdfReaderForResult(file.fileId());
                    }else {
                        Intent lIntent = new Intent();
                        lIntent.putExtra("file", file.fileId());

                        getActivity().setResult(Activity.RESULT_OK, lIntent);
                        getActivity().finish();
                    }

                }
            }else{
                if(file.isPdf()){
                    TQPdfReaderActivity.showRead(TQDirectoryFragment.this.getActivity(), file.fileId());
                }else if(file.isPng()){
                    String fileUrl = TQPictureUpload.downloadPath(file.fileId());
                    ArrayList<String> all = new ArrayList<>();
                    all.add(fileUrl);
                    DetailPicsActivity.jumpToThis(TQDirectoryFragment.this.getActivity(), all, 0);
                }else if(file.isMp4()){
                    String fileUrl = TQPictureUpload.downloadPath(file.fileId());
                    TQPlayerActivity.showPlayer(fileUrl, TQDirectoryFragment.this.getActivity());
                }
            }

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != Activity.RESULT_OK) return;

        if(requestCode == 0x11){
            getActivity().setResult(Activity.RESULT_OK, data);
            getActivity().finish();
        }
    }

    private void startPdfReaderForResult(String file){
        Intent lIntent = new Intent(getContext(), TQPdfReaderActivity.class);
        lIntent.putExtra(TQPdfReaderActivity.OPEN_TYPE_KEY, TQPdfReaderActivity.ACTIVITY_TYPE_SELECT);
        lIntent.putExtra(TQPdfReaderActivity.OPEN_PATH_KEY, file);
        startActivityForResult(lIntent, 0x11);
    }

    private void loadFile(){
        TQNetInterface.listUploadFile(loadFileType, page, new INetCallback() {
            @Override
            public void result(TQNetResult pNetResult) {
                Log.d(TAG, "result: ");
                boolean isRefresh = false;
                if(mRefreshLayout.getState() == RefreshState.Loading){
                    mRefreshLayout.finishLoadMore(pNetResult.isSuccess());
                }else{
                    mRefreshLayout.finishRefresh(pNetResult.isSuccess());
                    isRefresh = true;
                }

                if(!pNetResult.isSuccess() || pNetResult.getData() == null){
                    page--;
                    AlertDialogHelper.show(TQDirectoryFragment.this.getContext(), pNetResult.getErrMsg());
                    return;
                }

                JSONArray fileList = pNetResult.getData().optJSONArray("files");
                if(fileList != null){
                    ArrayList<TQDirectoryModel> lFileInfos = new ArrayList<>();
                    TQDirectoryModel lastModel = null;
                    for (int i = 0; i < fileList.length(); i++){
                        try {
                            JSONObject lObject = fileList.getJSONObject(i);
                            TQDirectoryModel.TQDirectoryItem lDirectoryModel = TQDirectoryModel.tagFromJson(lObject);

                            if(lastModel != null && lastModel.isSameDate(lDirectoryModel)){
                                lastModel.addTag(lDirectoryModel);
                            }else{
                                lastModel = new TQDirectoryModel();
                                lastModel.addTag(lDirectoryModel);

                                lFileInfos.add(lastModel);
                            }

                        }catch (JSONException e){
                            e.printStackTrace();
                        }
                    }

                    if(isRefresh){
                        mTQDirectoryAdapter.clear();
                    }
                    mTQDirectoryAdapter.appData(lFileInfos);

                    page = pNetResult.getData().optInt("page_no");
                    if(fileList.length() == 0){
                        //no data
                        page--;
                        mRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }
        });
    }
}
